'use client'

import { useEffect, useState } from 'react'
import { useAuth } from '@/contexts/AuthContext'
import { getTabToken, hasValidTabToken, getAllActiveTokens, getCacheInfo } from '@/lib/cache'

export default function TestAuthPage() {
  const { user, isAuthenticated, isLoading } = useAuth()
  const [cacheInfo, setCacheInfo] = useState<any>(null)
  const [activeTokens, setActiveTokens] = useState<any[]>([])
  const [currentToken, setCurrentToken] = useState<string | null>(null)
  const [hasValidToken, setHasValidToken] = useState<boolean>(false)

  useEffect(() => {
    // 获取缓存信息
    setCacheInfo(getCacheInfo())
    
    // 获取当前token
    setCurrentToken(getTabToken())
    
    // 检查token有效性
    setHasValidToken(hasValidTabToken())
    
    // 获取所有活跃token
    setActiveTokens(getAllActiveTokens())
  }, [])

  const refreshData = () => {
    setCacheInfo(getCacheInfo())
    setCurrentToken(getTabToken())
    setHasValidToken(hasValidTabToken())
    setActiveTokens(getAllActiveTokens())
  }

  return (
    <div className="p-6 max-w-4xl mx-auto">
      <h1 className="text-2xl font-bold mb-6">认证状态测试页面</h1>
      
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
        {/* 认证状态 */}
        <div className="bg-white p-4 rounded-lg shadow">
          <h2 className="text-lg font-semibold mb-4">认证状态</h2>
          <div className="space-y-2">
            <p><strong>加载中:</strong> {isLoading ? '是' : '否'}</p>
            <p><strong>已认证:</strong> {isAuthenticated ? '是' : '否'}</p>
            <p><strong>用户:</strong> {user ? `${user.username} (${user.role})` : '无'}</p>
          </div>
        </div>

        {/* Token状态 */}
        <div className="bg-white p-4 rounded-lg shadow">
          <h2 className="text-lg font-semibold mb-4">Token状态</h2>
          <div className="space-y-2">
            <p><strong>当前Token:</strong> {currentToken ? `${currentToken.substring(0, 20)}...` : '无'}</p>
            <p><strong>Token有效:</strong> {hasValidToken ? '是' : '否'}</p>
            <p><strong>Token长度:</strong> {currentToken ? currentToken.length : 0}</p>
          </div>
        </div>

        {/* 缓存信息 */}
        <div className="bg-white p-4 rounded-lg shadow">
          <h2 className="text-lg font-semibold mb-4">缓存信息</h2>
          {cacheInfo && (
            <div className="space-y-2">
              <p><strong>localStorage大小:</strong> {(cacheInfo.localStorage / 1024).toFixed(2)} KB</p>
              <p><strong>sessionStorage大小:</strong> {(cacheInfo.sessionStorage / 1024).toFixed(2)} KB</p>
              <p><strong>localStorage项目数:</strong> {cacheInfo.itemCount.localStorage}</p>
              <p><strong>sessionStorage项目数:</strong> {cacheInfo.itemCount.sessionStorage}</p>
            </div>
          )}
        </div>

        {/* 活跃Token列表 */}
        <div className="bg-white p-4 rounded-lg shadow">
          <h2 className="text-lg font-semibold mb-4">活跃Token列表</h2>
          <div className="space-y-2">
            {activeTokens.length > 0 ? (
              activeTokens.map((token, index) => (
                <div key={index} className="text-sm">
                  <p><strong>标签页:</strong> {token.tabId}</p>
                  <p><strong>Token:</strong> {token.token}</p>
                  <p><strong>最后活动:</strong> {new Date(token.lastActivity).toLocaleString()}</p>
                </div>
              ))
            ) : (
              <p className="text-gray-500">无活跃Token</p>
            )}
          </div>
        </div>
      </div>

      <div className="mt-6">
        <button
          onClick={refreshData}
          className="px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700"
        >
          刷新数据
        </button>
      </div>

      <div className="mt-6 bg-gray-100 p-4 rounded">
        <h3 className="font-semibold mb-2">调试说明:</h3>
        <ul className="text-sm space-y-1">
          <li>• 此页面用于测试认证状态和token管理</li>
          <li>• 页面刷新后，如果token有效，应该保持认证状态</li>
          <li>• 如果token无效或过期，应该自动清理并显示未认证状态</li>
          <li>• 缓存信息显示当前存储的数据大小和项目数量</li>
        </ul>
      </div>
    </div>
  )
}
